import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'utils/jsbridge.dart';
import 'register.dart';
import 'jsmethod.dart';

class OfflineWebViewPage extends StatefulWidget {
  const OfflineWebViewPage({super.key});

  @override
  State<StatefulWidget> createState() => _OfflineWebViewPage();
}

class _OfflineWebViewPage extends State<OfflineWebViewPage> {
  String locationStr = '';
  String title = 'WebView';
  String filePath = '';

  final InAppWebJSHandlerManager _inAppWebJSHandlerManager =
      InAppWebJSHandlerManager();

  late InAppWebJSBridgeRegister _inAppWebJSBridgeRegister;

  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
      crossPlatform: InAppWebViewOptions(
        applicationNameForUserAgent: "MyApp",
        userAgent: 'MyApp/1.0',
        // isInspectable: true,
        allowFileAccessFromFileURLs: true,
        allowUniversalAccessFromFileURLs: true,
        javaScriptEnabled: true,
        javaScriptCanOpenWindowsAutomatically: true,
        useOnLoadResource: true,
        preferredContentMode: UserPreferredContentMode.MOBILE,
        useShouldOverrideUrlLoading: true,
        clearCache: true,
      ),
      android: AndroidInAppWebViewOptions(
        useHybridComposition: true,
      ),
      ios: IOSInAppWebViewOptions(
        allowsInlineMediaPlayback: true,
      ));

  InAppWebViewController? webViewController;
  final GlobalKey webViewKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    filePath = Get.arguments["filePath"];
    _inAppWebJSBridgeRegister =
        InAppWebJSBridgeRegister(_inAppWebJSHandlerManager);
  }

  @override
  Widget build(BuildContext context) {
    String fileStr = '$filePath/index.html';
    print('准备访问的页面：$fileStr');
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
          title: Text(title),
        ),
        body: InAppWebView(
          key: webViewKey,
          initialUrlRequest: URLRequest(url: Uri.file(fileStr)),
          // initialFile: fileStr,
          initialOptions: options,
          onWebViewCreated: (controller) async {
            print('onWebViewCreated $controller');
            webViewController = controller;
            _inAppWebJSHandlerManager.updateController(
              context: context,
              inAppWebViewController: webViewController,
            );
            _inAppWebJSHandlerManager.injectJavascriptReady();
            _inAppWebJSBridgeRegister.registerHandlers(
                jsChannelRegisterHandler: (handleName, data) {
              if (handleName == JSChannelRegisterMethod.setTitle) {
                setState(() {
                  title = data;
                });
              }
            });
          },
          onLoadResource: (controller, resource) {
            print('onLoadResource $resource');
          },
          onTitleChanged: (controller, t) {
            setState(() {
              title = t ?? "";
            });
          },
          onLoadStart: (controller, url) {
            print('onLoadStart $url');
          },
          onLoadError: (controller, url, code, message) {
            print('onLoadError $url $code $message');
          },
          onLoadStop: (controller, url) {
            // 注入
            _inAppWebJSHandlerManager.injectBridgeJavascript();

            _inAppWebJSHandlerManager.checkJavascriptBridge();
          },
        ));
  }
}
